package gui;

import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.basic.BasicBorders.ToggleButtonBorder;

import classes.ConnectionDB;
import classes.ExamGeneralDetails;
import classes.QuestionSelection;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AddingDesiredQuestions extends javax.swing.JFrame {

	private static int framesCount = -1; /* is as the number of topics */
	private static ArrayList<QuestionSelection> questionsData = new ArrayList<QuestionSelection>();

	public AddingDesiredQuestions(final Properties langFile,
			final int numberOfTopics, final ArrayList<JFrame> frames,
			final ArrayList<ExamGeneralDetails> data,
			final ArrayList<String> subTopics) throws SQLException {

		final JFrame frame = new JFrame("JOptionPane showMessageDialog example");
		frames.add(this);
		framesCount++;

		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		this.setUndecorated(true);

		final Connection connection = new ConnectionDB().createConnection();
		Statement statement = connection.createStatement();

		DefaultListModel topicsModel = new DefaultListModel();
		final DefaultListModel subtopicsModel = new DefaultListModel();
		final DefaultListModel questionsModel = new DefaultListModel();

		setBackground(Color.DARK_GRAY);
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		final JList TopicsList = new JList(topicsModel);
		TopicsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		TopicsList.setVisibleRowCount(30);
		final JList subtopicsList = new JList(subtopicsModel);
		subtopicsList.setVisibleRowCount(30);
		final JList questionsList = new JList(questionsModel);
		questionsList.setVisibleRowCount(30);
		Container c = getContentPane();
		JScrollPane sp1 = new JScrollPane(TopicsList);
		JLabel lblTopics = new JLabel("Topics");
		lblTopics.setFont(new Font("Tahoma", Font.BOLD, 13));
		lblTopics.setHorizontalAlignment(SwingConstants.CENTER);
		lblTopics.setBackground(Color.DARK_GRAY);
		sp1.setColumnHeaderView(lblTopics);
		JScrollPane sp2 = new JScrollPane(subtopicsList);
		JLabel label = new JLabel("Subtopics");
		label.setFont(new Font("Tahoma", Font.BOLD, 13));
		label.setHorizontalAlignment(SwingConstants.CENTER);
		sp2.setColumnHeaderView(label);
		JScrollPane sp3 = new JScrollPane(questionsList);
		JLabel label_1 = new JLabel("Quesiotns");
		label_1.setFont(new Font("Tahoma", Font.BOLD, 13));
		label_1.setHorizontalAlignment(SwingConstants.CENTER);
		sp3.setColumnHeaderView(label_1);
		Box box = Box.createHorizontalBox();
		box.setBackground(Color.DARK_GRAY);
		box.add(sp1);
		box.add(sp2);
		box.add(sp3);
		c.add(box, BorderLayout.CENTER);

		JButton btnBack = new JButton("Back");
		box.add(btnBack);
		btnBack.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				frames.get(framesCount).setVisible(false);
				frames.get(framesCount - 1).setVisible(true);
				framesCount--;
			}
		});

		JButton next = new JButton("Next");
		box.add(next);
		if (framesCount == (numberOfTopics - 1)) {
			next.setText("Create");
		}
		next.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String SelTopic = (String) TopicsList.getSelectedValue();
				Object selSubTopics[] = subtopicsList.getSelectedValues();
				Object selQuestions[] = questionsList.getSelectedValues();

				if (framesCount == (numberOfTopics - 1)) {
					QuestionSelection info = new QuestionSelection(data
							.get(0).getName(), SelTopic, selSubTopics,
							selQuestions, Integer.parseInt(subTopics
									.get(framesCount)));
					questionsData.add(framesCount, info);
					try {
						Statement st = connection.createStatement();
						st.executeUpdate("INSERT INTO Exams VALUES ('"
								+ data.get(0).getName() + "','"
								+ data.get(0).getNumOfQuestions() + "','"
								+ data.get(0).getHrDuration() + "','"
								+ data.get(0).getMinDuration() + "','"
								+ data.get(0).getLowestWeight() + "','"
								+ data.get(0).getHighestWeight() + "','"
								+ data.get(0).getNumberOfTopics() + "')");
					for(int j=0; j<numberOfTopics; j++){	
						for(int i=0; i<questionsData.get(j).getQuestion().length; i++){
							PreparedStatement stat = connection.prepareStatement("SELECT subtopic FROM SAVEQA WHERE question = ?");
							//TODO -- CHANGE question OR NOT
							stat.setString(1,(String)questionsData.get(j).getQuestion()[i]);
							ResultSet res = stat.executeQuery();
							res.next();
							String subTopicName = res.getString("subtopic");
							st.executeUpdate("INSERT INTO Qtable VALUES ('"
									+ data.get(0).getName() + "','"
									+ questionsData.get(j).getTopic() + "','"
									+ subTopicName + "','"
									+ (String)questionsData.get(j).getQuestion()[i] + "','"
									+ Integer.parseInt(subTopics.get(j)) + "')");
						}
					}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}

					JOptionPane.showMessageDialog(
							frame,
							langFile.getProperty("usr.menu.file.addExam.alert.examCreated"));
					frames.get(framesCount).setVisible(false);
					frames.get(0).setVisible(false);
				}

				else {
					try {
						if (frames.get(framesCount + 1) != null) {
							frames.get(framesCount).setVisible(false);
							frames.get(framesCount + 1).setVisible(true);
							questionsData.get(framesCount)
									.updateValues(
											data.get(0).getName(),
											SelTopic,
											selSubTopics,
											selQuestions,
											Integer.parseInt(subTopics
													.get(framesCount)));
							framesCount++;
						}
					} catch (IndexOutOfBoundsException e1) {
						frames.get(framesCount).setVisible(false);
						QuestionSelection info = new QuestionSelection(data
								.get(0).getName(), SelTopic, selSubTopics,
								selQuestions, Integer.parseInt(subTopics
										.get(framesCount)));
						questionsData.add(framesCount, info);
						try {
							new AddingDesiredQuestions(langFile,
									numberOfTopics, frames, data, subTopics)
									.setVisible(true);
						} catch (SQLException e2) {
							e2.printStackTrace();
						}
						e1.printStackTrace();
					}
				}
			}
		});

		final ResultSet result = statement
				.executeQuery("SELECT topic FROM TOPSUB");

		while (result.next()) {
			topicsModel.addElement(result.getString("topic"));
		}

		ListSelectionModel selectionModel = TopicsList.getSelectionModel();
		selectionModel.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				PreparedStatement st;
				subtopicsList.clearSelection();
				subtopicsList.removeAll();
				try {
					st = connection
							.prepareStatement("SELECT subtopic FROM TOPSUB WHERE topic = ?");
					st.setString(1, ((String) TopicsList.getSelectedValue()));
					ResultSet res = st.executeQuery();

					while (res.next()) {
						subtopicsModel.addElement(res.getString("subtopic"));
					}

				} catch (SQLException e1) {
					e1.printStackTrace();
				}

			}
		});
		
		ListSelectionModel slecModel = subtopicsList.getSelectionModel();
		subtopicsList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				PreparedStatement st;
				questionsList.clearSelection();
				questionsList.removeAll();
				try {
					st = connection
							.prepareStatement("SELECT question FROM SAVEQA WHERE subtopic = ?");
					String s = (String) subtopicsList.getSelectedValue();
					st.setString(1, ((String) subtopicsList.getSelectedValue()));
					ResultSet res = st.executeQuery();

					while (res.next()) {
						questionsModel.addElement(res.getString("question"));
					}

				} catch (SQLException e1) {
					e1.printStackTrace();
				}

			}
		});

	}

	public static void main(String args[]) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AddingDesiredQuestions frame = new AddingDesiredQuestions(
							null, -1, null, null, null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

}
